package com.opdar.athena.client.agent.task;

import com.opdar.athena.client.agent.base.Configuration;
import com.opdar.athena.client.agent.server.IoSession;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by shiju on 2017/6/30.
 */
public class UserBindCheckTask implements Runnable {
    private final ChannelHandlerContext ctx;
    private int checkFrequency = 0;
    private final static Logger logger = LoggerFactory.getLogger(UserBindCheckTask.class);
    private boolean isStop = false;

    public UserBindCheckTask(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    @Override
    public void run() {
        if(!isStop){
            IoSession ioSession = Configuration.getConfiguration().getSession(ctx);
            if(ioSession.getToken() == null){
                //bind is failure.
                checkFrequency++;
                if(checkFrequency == Configuration.getConfiguration().getCheckFrequency()){
                    ioSession.downline();
                }else{
                    logger.info("目前计数[{}]达到计数[{}]时将自动关闭该会话.",checkFrequency,Configuration.getConfiguration().getCheckFrequency());
                    ctx.executor().schedule(this, Configuration.getConfiguration().getCheckTime(), TimeUnit.MILLISECONDS);
                }
            }
        }
    }

    public static UserBindCheckTask start(ChannelHandlerContext ctx) {
        UserBindCheckTask task = null;
        ctx.executor().schedule(task = new UserBindCheckTask(ctx), Configuration.getConfiguration().getCheckTime(), TimeUnit.MILLISECONDS);
        return task;
    }

    public void stop() {
        isStop = true;
    }
}
